package pl.edu.agh.pros.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.jivesoftware.smack.packet.Message;
import org.ros.node.Node;

import pl.edu.agh.pros.prop.Props;

public final class RosServiceUtils {

	private RosServiceUtils() {

	}

	public static Message serializeServiceRequest(org.ros.internal.message.Message request, Node node, String type) {
		ByteBuffer buffer = node.getMessageSerializationFactory().newServiceRequestSerializer(type).serialize(request);
		byte[] bytes = new byte[buffer.capacity()];
		buffer.get(bytes);
		Message chatMessage = new Message();
		chatMessage.setBody(Props.XMPP_MSG_BODY);
		chatMessage.setProperty(Props.XMPP_MSG_VALUE, bytes);
		chatMessage.setProperty(Props.XMPP_MSG_TYPE, type);
		return chatMessage;
	}

	public static org.ros.internal.message.Message deserializeServiceRequest(Message message, Node node, String type) {
		ByteBuffer buffer = ByteBuffer.wrap((byte[]) message.getProperty(Props.XMPP_MSG_VALUE));
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		org.ros.internal.message.Message msg = (org.ros.internal.message.Message) node.getMessageSerializationFactory()
				.newServiceRequestDeserializer(type).deserialize(buffer);
		return msg;
	}

	public static Message serializeServiceResponse(org.ros.internal.message.Message response, Node node, String type) {
		ByteBuffer buffer = node.getMessageSerializationFactory().newServiceResponseSerializer(type)
				.serialize(response);
		byte[] bytes = new byte[buffer.capacity()];
		buffer.get(bytes);
		Message chatMessage = new Message();
		chatMessage.setBody(Props.XMPP_MSG_BODY);
		chatMessage.setProperty(Props.XMPP_MSG_VALUE, bytes);
		chatMessage.setProperty(Props.XMPP_MSG_TYPE, type);
		return chatMessage;
	}

	public static org.ros.internal.message.Message deserializeServiceResponse(Message message, Node node, String type) {
		ByteBuffer buffer = ByteBuffer.wrap((byte[]) message.getProperty(Props.XMPP_MSG_VALUE));
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		org.ros.internal.message.Message msg = (org.ros.internal.message.Message) node.getMessageSerializationFactory()
				.newServiceResponseDeserializer(type).deserialize(buffer);
		return msg;
	}

}
